//
//  printReadBuff.m
//  serialTest
//
//  Created by mt-007 on 2021/4/1.
//

#import "printReadBuff.h"

@implementation printReadBuff

/**
 * @brief print the read buff content, switch the mode, character or binary or octonary or hexadecimal mode to output.
 *
 * @param readBuff input content.
 * @param length input content length.
 * @param mode (char) out put mode.
 *
 */
+ (void)print:(char *)readBuff
    andLength:(ssize_t)length
      andMode:(char)mode {
    if(mode == 'c') {
        [self printByChar:readBuff
                andLength:length];
    } else if(mode == 'b') {
        [self printByBinary:readBuff
                andLength:length];
    } else if(mode == 'o') {
        [self printByOctonary:readBuff
                andLength:length];
    } else if(mode == 'h') {
        [self printByHexadecimal:readBuff
                andLength:length];
    }
}


/**
 * print by char
 */
+ (void)printByChar:(char *)readBuff andLength:(ssize_t)length {
    for(int i = 0; i < length; i++){
        printf("%c", readBuff[i]);
    }
}

/**
 * print by binary
 * C launage did have the function of print binary number.
 * So we should create one by my self.
 */
+ (void)printByBinary:(char *)readBuff andLength:(ssize_t)length {
    for(int i = 0; i < length; i++){
        int tmpBuff = readBuff[i];
        //printf("%c", readBuff[i]);
        print_bin(tmpBuff);
        printf(" ");
    }
    printf("\n");
}

/**
 * print by octonary
 */
+ (void)printByOctonary:(char *)readBuff andLength:(ssize_t)length {
    for(int i = 0; i < length; i++){
        int tmpBuff = readBuff[i];
        printf("%#o ", tmpBuff);
    }
    printf("\n");
}

/**
 * print by hexadecimal
 */
+ (void)printByHexadecimal:(char *)readBuff andLength:(ssize_t)length {
    for(int i = 0; i < length; i++){
        int tmpBuff = readBuff[i];
        printf("%#x ", tmpBuff);
    }
    printf("\n");
}

/**
 * C launage code: print the binary number.
 */
void print_bin(int n) {
    int l = sizeof(n)*8;
    int i = 0;
    if(n == 0) {
        printf("0");
        return;
    }
    
    for(i = l-1; i >= 0; i --) {
        if(n&(1<<i)) {
            break;
        }
    }
    for(;i>=0; i --) {
        printf("%d", (n&(1<<i)) != 0);
    }
}

@end
